<?php
namespace app\yunda\home;

use app\yunda\model\System;
use app\yunda\model\Order as OrderModel;
use app\yunda\model\Danhao;
use app\yunda\model\BatchOrder;
use app\yunda\model\Category;
use app\yunda\model\Address;
use app\yunda\model\Youhui;
use app\yunda\model\User as UserModel;

/**
 * 寄快递
 * @package app\yunda\home
 */
class Order extends Base {
    // 获取列表
    public function index(){
        // 查询字段
        $map = $this->getMap();
        $search=request()->only(['order_status','openid']);//订单状态筛选
        if(!isset($search['openid'])||empty($search['openid'])) return mogo_error('参数错误',404);
        $map['openid']=$search['openid'];
        $map['order_status']=1;//默认获取未签收订单
        if(isset($search['order_status']) && !empty($search['order_status'])){
            $map['order_status']=$search['order_status'];
        }
        $Address = new OrderModel();

        // 自定义where查询
        $data =  $Address
            ->where($map)
            ->order('id desc')
            ->paginate()
            ->each(function($item){
                $item['send_id']=(new Address())->getAddress($item['send_id']);
                $item['get_id']=(new Address())->getAddress($item['get_id']);
                $c=explode(",",$item['send_id']['home_1']);
                $c1=explode(",",$item['get_id']['home_1']);
                if($c)$item['send_city']=$c[1];
                if($c)$item['get_city']=$c1[1];
                $item['update_time']=format_time($item['update_time']);
                $arr=[1=>'待确认',2=>'待取件',3=>'已取件',4=>'已派送',5=>'已取消'];
                $item['status']=$arr[$item['order_status']];
                $aa=implode($c).$item['send_id']['address'];
                //halt(implode($c));
                $item['longitude']=getLatLng($aa)['lng'];
                $item['latitude']=getLatLng($aa)['lat'];
                unset($item['send_id']);
                unset($item['get_id']);
                if($item['pay_money']>0 && $item['is_pay_money']==0){
                    $item['is_zf']=1;
                }else{
                    $item['is_zf']=0;
                }
                return $item;
            });
        $data = $data->toArray();
        return mogo_json($data);
    }
    // 生成订单
    public function save(){
        // 第一步 过滤字段
        $data = request()->only(['openid','get_id', 'send_id','order_type','weight','is_pay','is_price','ask']);
        // 第二部 验证字段
        $result = $this->validate($data,'Order');
        if(true!==$result){
            return mogo_error($result,404);
        }
//        //使用优惠券
//        if(isset($data['youhui_id']) && !empty($data['youhui_id'])){
//            $youhui=Youhui::get($data['youhui_id']);
//            if(empty($youhui)) return mogo_error('优惠券不存在',404);
//        }
        $send_address=(new Address())->getAddress($data['send_id']);
        if(!empty($send_address)){
            $data['send_address']=str_replace(',', '', $send_address['home_1']).$send_address['address'];
            $data['send_name']=$send_address['name'];
            $data['send_phone']=$send_address['phone'];
        }

        $get_address=(new Address())->getAddress($data['get_id']);
        if(!empty($get_address)){
            $data['get_address']=str_replace(',', '', $get_address['home_1']).$get_address['address'];
            $data['get_name']=$get_address['name'];
            $data['get_phone']=$get_address['phone'];
        }
        $poster_code=OrderModel::youMaCode();
        $data['poster_code']=$poster_code;

        $data['order_status']=1;//待取件
         $res = OrderModel::create($data);//新增
        return mogo_json($res,'下单成功',1);
    }
    // 订单详情
    public function read($id){
        $body=request()->only(['openid','id']);
        if(empty($body['id'])||empty($body['openid'])) return mogo_error('参数错误',404);
//        $data = OrderModel::get(['id'=>$body['id'],'openid'=>$body['openid']]);
        $data = OrderModel::get(['id'=>$body['id']]);
//        $data=OrderModel::view('yd_order o')
//            ->view('yd_address a','name send_name,phone send_phone,home_1,addres','a.id=o.send_id','left')
//            ->view('yd_address a1','name,phone,home_1,address','a1.id=o.get_id','left')
//            ->view('yd_category c','name order_type_name','c.id=o.order_type','left')
//            ->where(['o.id'=>$id])
//            ->find();
        // 第一步 验存
        if(!$data) return mogo_error('订单不存在',404);
        $data['order_type']=Category::getOne($data['order_type']);
        $arr=[0=>'未知',1=>'待确认',2=>'待取件',3=>'已取件',4=>'已派送',5=>'已取消'];
        $data['status']=$arr[$data['order_status']];
        // 这里可以做一些处理
        return mogo_json($data,'ok',1);
    }
    //最新订单
    public function new_order(){
        $body=request()->only('openid');
        if(empty($body['openid']))return mogo_error('用户参数错误',404);
        $user=UserModel::get(['openid'=>$body['openid']]);
        if(empty($user)) return mogo_error('用户不存在');
        $limit=config('new_order_num');
        if(empty($limit)) $limit=2;
        if($limit>=5) $limit=5;
        $data = OrderModel::view('yd_order o','*')
            ->view('yd_user u','name','u.openid=o.openid','left')
            ->where(['o.openid'=>$body['openid'],'o.order_status'=>1])
            ->limit($limit)
            ->order('o.id desc')
            ->select();
        foreach ($data as &$v){
            $send_id=(new Address())->getAddress($v['send_id']);
            $get_id=(new Address())->getAddress($v['get_id']);
            $c=explode(",",$send_id['home_1']);
            $c1=explode(",",$get_id['home_1']);
            if($c)$v['send_city']=$c[1];
            if($c)$v['get_city']=$c1[1];
            $v['update_time']=format_time($v['update_time']);
            $arr=[1=>'待确认',2=>'待取件',3=>'已取件',4=>'已派送',5=>'已取消'];
            $v['status']=$arr[$v['order_status']];
        }
        return mogo_json($data,'最新订单');
    }

    //取消订单
    public function cancel_order($id)
    {
        $data=request()->only('cancel_reason');
        if(empty($id))return mogo_error('参数错误',404);
        $row=OrderModel::get($id);
        if(empty($row)) return mogo_error('订单不存在',404);
        if($row['order_status']==3) return mogo_error('该订单不能取消',404);
        if($row['order_status']==5) return mogo_error('订单已取消,请勿重复操作',404);
//        if($row['is_pay_money']==1 && !empty($row['pay_money']))
//            return mogo_error('该订单已支付，不能取消',404);
        $data['id']=$id;
        $data['order_status']=5;//已取消
//        halt($data);
        $res=OrderModel::update($data);
        return mogo_json($res,'',1);
    }

    //批量寄件
    public function batch_send($openid='')
    {
        if(empty($openid)) return mogo_error('参数错误',404);
        //判断用户是否是韵达会员
        $data=request()->only('content');

//        $result = $this->validate($data,'BatchOrder');
//        if(true!==$result){
//            return mogo_error($result);
//        }
        //假设格式通过
        $data['content']=rtrim($data['content'],';');
        $content=explode(';',$data['content']);
        foreach ($content as $k=>&$v){
            $v=explode(',',$v);

        }
        //本次寄件条数统计
        $order_number=count($content);
        //系统配置单次批量寄件条数限制
        $limit=System::getSystemConfig('batch_number');
        if($order_number>$limit) return mogo_error('单次批量寄件条数不能超过'.$limit,0);
        $arr=[];
        //查询
        for($i=0;$i<count($content);$i++){
                $arr[$i]['get_name']=$content[$i][0];
                $arr[$i]['phone']=$content[$i][1];
                $arr[$i]['address']=$content[$i][2];
                $arr[$i]['goood_type']=$content[$i][3];
        }
        halt($arr);
        $model=new BatchOrder();
        $res=$model->saveAll($arr);
        return mogo_json($res,'',1);
    }

    //填写订单号
    public function dingDanHao()
    {
//        $data=request()->only(['id','order_id','pay_money']);
        $data=request()->only(['id','order_id','openid']);
        if(empty($data['openid']))return mogo_error('业务员openid不能为空',404);
        $user=User::get(['openid'=>$data['openid']]);
        if(empty($user)) return mogo_error('业务员不存在',404);
        if(!isset($data['id']) || !is_numeric($data['id'])) return mogo_error('参数错误',404);
        $result=$this->validate($data,'Ddh');
        if($result!==true) return mogo_error($result,404);
        $danhao=Danhao::get(['is_use'=>0,'order_sn'=>$data['order_id']]);
        if(empty($danhao))return mogo_error('请输入正确的运单号');
        $dingdan=OrderModel::get($data['id']);
        if(empty($dingdan))return mogo_error('订单不存在');

        halt($data);
        //更新填写的运单号的状态
        Danhao::update(['id'=>$danhao['id'],'is_use'=>1]);
        //更新用户订单信息
        $res=OrderModel::update([
            'id'=>$data['id'],
            'order_id'=>$data['order_id'],
        ]);
        return mogo_json($res,'',1);

    }

    //支付订单
    public function pay_postage()
    {
        $body=request()->only(['id','openid']);
        $user=User::get(['openid'=>$body['openid']]);
    }

    //获取快递物品类型
    public function get_goods()
    {
        $list=(new Category())->getGood();
        return mogo_json($list,'',1);
    }


}